package day_2022_7_to_8.day48;

/**
 * @author haomin
 * @date 2022/08/18 22:23
 **/
public class Day33_4_Num67_AddBinary {
    class Solution {
        public String addBinary(String a1, String b1) {
            StringBuffer a = new StringBuffer(a1).reverse();
            StringBuffer b = new StringBuffer(b1).reverse();
            int len = Math.max(a.length(),b.length());
            int flag = 0;
            StringBuffer sb = new StringBuffer();
            for(int i = 0;i < len;i++){
                if(i >= a.length()){          // a走完了
                    System.out.println(1);
                    if((b.charAt(i)-48) + flag == 0) {
                        sb.append(0);
                    }else if((b.charAt(i)-48) + flag == 1){
                        sb.append(1);
                        flag = 0;
                    }else if((b.charAt(i)-48) + flag == 2){
                        sb.append(0);
                        flag = 1;
                    }
                }else if(i >= b.length()){    // b走完了
                    if((a.charAt(i)-48) + flag == 0) {
                        sb.append(0);
                    }else if((a.charAt(i)-48) + flag == 1){
                        sb.append(1);
                        flag = 0;
                    }else if((a.charAt(i)-48) + flag == 2){
                        sb.append(0);
                        flag = 1;
                    }
                }else if((b.charAt(i)-48) + (a.charAt(i)-48) + flag == 0){
                    sb.append(0);
                }else if((b.charAt(i)-48) + (a.charAt(i)-48) + flag == 1){
                    sb.append(1);
                    flag = 0;
                }else if((b.charAt(i)-48) + (a.charAt(i)-48) + flag == 2){
                    sb.append(0);
                    flag = 1;
                }else if((b.charAt(i)-48) + (a.charAt(i)-48) + flag == 3){
                    sb.append(1);
                    flag = 1;
                }
            }
            if(flag == 1) sb.append(1);
            return sb.reverse().toString();
        }
    }




    // （转十进制再转二进制）超时
    class Solution2 {
        public String addBinary(String a, String b) {
            return ToBinary(ToDecimal(a) + ToDecimal(b));
        }

        private int ToDecimal(String str) {
            int sum = 0;
            for(int i = str.length()-1,j = 0;i >= 0;--i,++j){
                if(str.charAt(i) == '1'){
                    sum += Math.pow(2,j);
                }
            }
            return sum;
        }

        private String ToBinary(int num) {
            StringBuffer sb = new StringBuffer();
            while (num != 1){
                if(num % 2 == 0){
                    sb.append(0);
                    num/=2;
                }else if(num % 2 == 1){
                    sb.append(1);
                    num/=2;
                }
            }
            sb.append(1);
            sb = sb.reverse();
            return sb.toString();
        }
    }
}